﻿#include "ElementTreeItem.h"

ElementTreeItem::ElementTreeItem()
    :mParent(nullptr)
    ,mValues({})
    ,mChildren({})
{

}

int ElementTreeItem::rowOnParent() const
{
    if(!mParent){
        return -1;
    }
    return mParent->mChildren.indexOf(this);
}

ElementTreeItem *ElementTreeItem::child(int index)
{
    if(index<0||index>=mChildren.size())
        return nullptr;
    return mChildren[index];
}

void ElementTreeItem::setParentToNull()
{
    if(mParent)
        mParent->mChildren.removeAt(rowOnParent());
    mParent=nullptr;
}

bool ElementTreeItem::appendChild(ElementTreeItem *child)
{
    return insertChild(mChildren.size(),child);
}

bool ElementTreeItem::insertChild(int index, ElementTreeItem *child)
{
    if(index<0||index>childrenCount()||!child){
        return false;
    }
    ElementTreeItem *parent = child->parent();
    if(parent){
        parent->mChildren.removeAt(child->rowOnParent());
    }
    child->mParent = this;
    mChildren.insert(index,child);
    return true;
}

QVariant ElementTreeItem::value(int dataRole) const{
    if(mValues.find(dataRole)==mValues.end())
        return QVariant();
    return mValues[dataRole];
}

void ElementTreeItem::setValue(int dataRole, const QVariant &v)
{
    mValues[dataRole] = v;
}
void ElementTreeItem::setValue(int dataRole, QVariant &&v)
{
    mValues[dataRole] = v;
}
